package com.linran.utils.utils;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.StringUtils;

import java.util.Objects;

public class SpringElEvaluateUtil {

    public static EvaluationContext createEvaluationContext(String[] paramNames, Object[] args) {
        EvaluationContext context = new StandardEvaluationContext();
        if (Objects.nonNull(paramNames)) {
            for (int i = 0; i < args.length; i++) {
                String pName = paramNames[i];
                if (!StringUtils.isEmpty(pName)) {
                    context.setVariable(pName, args[i]);
                }
            }
        }
        return context;
    }

    public static String evaluateExpression(SpelExpressionParser spelExpressionParser,
                                            EvaluationContext context, String el) {
        Expression expression = spelExpressionParser.parseExpression(el);
        return String.valueOf(expression.getValue(context));
    }
}
